package com.ruoyi.project.app.aspect.handler;

import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Field;
import java.lang.reflect.Parameter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ValidParamHandler implements Handler {

    private List<Handler> validParamChainHandler = new ArrayList<>();
    {
        validParamChainHandler.add(new NotNullHandler());//null
        validParamChainHandler.add(new NotEmptyHandler());//空值，“null”，“undefined”
        validParamChainHandler.add(new CheckEmailHandler());//邮箱格式
        validParamChainHandler.add(new CheckUserHandler());//用户是否存在检查
    }

    @Override
    public boolean handler(AnnotatedElement element, Object obj) throws IllegalAccessException {
        //到这里一定是参数标注了ValidParam注解

        Class<?> paramClazz = null;
        if(element instanceof Parameter){
            Parameter  parameter = (Parameter) element;
            paramClazz = parameter.getType();
        }else if(element instanceof Field){
            Field field = (Field) element;
            paramClazz = field.getType();
        }

        //获取类型所对应的参数对象，实际项目中Controller中的接口不会传两个相同的自定义类型的参数，所以此处直接使用findFirst()
        Class<?> finalParamClazz = paramClazz;
        Object arg = Arrays.stream((Object[])obj).filter(ar -> finalParamClazz.isAssignableFrom(ar.getClass())).findFirst().get();
        //得到参数的所有成员变量
        Field[] declaredFields = paramClazz.getDeclaredFields();
        for (Field field : declaredFields) {
            field.setAccessible(true);
            //二次责任链
            for(Handler handler:validParamChainHandler){
                handler.handler(field,field.get(arg));
            }
        }
        return false;
    }
}
